package cn.bone.web.system.realm;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * Created by superbone on 2017/4/19.
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private SessionDAO sessionDAO;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {



        return null;
    }

    /**
     * 认证信息(身份验证) Authentication 是用来验证用户身份
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String)token.getPrincipal();
        System.out.println(JSON.toJSONString(token));
    /*// 调用userService查询是否有此用户
        User user = userService.findUserByUsername(username);
        if (user == null) {
            // 抛出 帐号找不到异常
            throw new UnknownAccountException();
        }
        // 判断帐号是否锁定
        if (Boolean.TRUE.equals(user.getLocked())) {
            // 抛出 帐号锁定异常
            throw new LockedAccountException();
        }*/

        Collection<Session> activeSessions = sessionDAO.getActiveSessions();
        for(Session session : activeSessions){
            //获得session中已经登录用户的名字
            String loginUsername =  String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
            if(username.equals(loginUsername)){  //这里的username也就是当前登录的username
                session.setTimeout(0);  //这里就把session清除，
            }
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                "admin",
                "123456",
                "superbone");

        return info;
    }
}
